﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IGolovkine.Core;
using IGolovkine.ShoutCastRipper.Service.Configuration;
using IGolovkine.ShoutCastRipper.Testing.ConnectionRecorder;
using System.Xml;
using System.IO;

namespace IGolovkine.ShoutCastRipper.Service.Console
{
    public class ConsoleStationRipperService: StationRipperService
    {
        public ConsoleStationRipperService(StationRipperElement p)
            : base(p)
        { 
        }
        
        protected override TypeFactory<IStationClient> CreateStationClientFactory(StationRipperElement p, TypeFactory<IStationConnection> connectionFactory, ILogWriter logWriter)
        {
            string folder = Settings.Default.ConnectionRecorderFolder;
            string url = p.Url.ToLower();
            bool remote = url.Contains("http");
            if (remote)
            {
                if (!string.IsNullOrEmpty(folder))
                {
                    TypeFactory<IStationClientEventWriter> writerFactory = ()=> new XmlStationClientEventWriter(() => this.CreateXmlTextWriter(p, folder));
                    return () => new StationClientEventRecorder(() => new StationClient(connectionFactory), writerFactory);
                }
            }
            
            return base.CreateStationClientFactory(p, connectionFactory, logWriter);
        }

        private XmlTextWriter CreateXmlTextWriter(StationRipperElement p, string folder)
        {
            string fileName = string.Format("{0}_Events_{1:yyyy_MMM_dd_HH_mm_ss}.xml", p.Name, DateTime.Now);
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            string path = Path.Combine(folder, fileName);
            return new XmlTextWriter(path, Encoding.Unicode); 
        }

        private XmlTextReader CreateXmlTextReader(string url)
        {
            return new XmlTextReader(new FileStream(url, FileMode.Open));
        }

      

    }
}
